package com.android.lovely.ui.activity

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextPaint
import android.text.format.DateUtils
import android.text.style.ClickableSpan
import android.view.View
import android.view.ViewGroup.MarginLayoutParams
import androidx.activity.OnBackPressedCallback
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.core.view.updateLayoutParams
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.android.lovely.BuildConfig
import com.android.lovely.R
import com.android.lovely.aav.PreferentialManager
import com.android.lovely.aav.lifecycle.LovelyLifecycleManager
import com.android.lovely.admob.AdmobManager
import com.android.lovely.const.HomeSelect
import com.android.lovely.const.HomeShowRole
import com.android.lovely.const.HomeShowTask
import com.android.lovely.data.getInviteInfo
import com.android.lovely.databinding.ActivityHomeBinding
import com.android.lovely.ext.fullScreen
import com.android.lovely.ext.setNotifyPermission
import com.android.lovely.framework.BaseActivity
import com.android.lovely.framework.BaseDialogFragment
import com.android.lovely.framework.BaseDialogFragment.OnDialogListener
import com.android.lovely.framework.UIController.showToast
import com.android.lovely.manager.KVStore
import com.android.lovely.ui.dialog.AdultDialog
import com.android.lovely.ui.dialog.AppUpgradeDialog
import com.android.lovely.ui.dialog.PreferentialDialog
import com.android.lovely.ui.dialog.SignDialog
import com.android.lovely.ui.dialog.showLovelyDialog
import com.android.lovely.ui.fragment.ChatMsgFragment
import com.android.lovely.ui.fragment.HomeFragment
import com.android.lovely.ui.fragment.MineFragment
import com.android.lovely.user.UserManager
import com.google.android.ump.ConsentDebugSettings
import com.google.android.ump.ConsentInformation
import com.google.android.ump.ConsentRequestParameters
import com.google.android.ump.UserMessagingPlatform
import com.kotlin.extensions.bus.FlowBus
import com.kotlin.extensions.bus.flowOf
import com.kotlin.extensions.bus.post
import com.kotlin.extensions.context.ActivityExt.navBarHeight
import com.kotlin.extensions.context.ContextExt.startPage
import com.kotlin.extensions.dimen.Dimension.dp
import com.kotlin.extensions.view.ViewExt.clickable
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch

/**
 *
 * @author why
 * @date 2025/3/8 20:13
 */
class HomeActivity : BaseActivity<ActivityHomeBinding>() {

    private var doubleExit = false

    private val launcher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { activityResult ->
        showLovelyLifecycle()
    }

    private val lifecycleLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { activityResult ->
        showNotifyPermission()
    }

    private var lastPosition = 0
    override fun initView(savedInstanceState: Bundle?) {
        fullScreen()
        getInviteInfo()
        mBinding.fragment.isUserInputEnabled = false
        mBinding.fragment.adapter = FragmentAdapter()
        mBinding.fragment.offscreenPageLimit = 3
        mBinding.fragment.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                selectTab(position)
            }
        })

        mBinding.home.clickable {
            if(mBinding.flCreateDialog.isVisible) {
                dismissDialog()
            } else {
                selectTab(0)
            }

        }
        mBinding.chat.clickable {
            if(mBinding.flCreateDialog.isVisible) {
                dismissDialog()
            } else {
                selectTab(1)
            }
        }
        mBinding.mine.clickable {
            if(mBinding.flCreateDialog.isVisible) {
                dismissDialog()
            } else {
                selectTab(2)
            }
        }
        mBinding.flCreateDialog.clickable {
            dismissDialog()
        }
        mBinding.create.clickable {
            if(mBinding.flCreateDialog.isVisible) {
                dismissDialog()
            } else {
                mBinding.home.isSelected = false
                mBinding.chat.isSelected = false
                mBinding.mine.isSelected = false
                mBinding.create.isSelected = true
                mBinding.llCreateDialog.isVisible = true
                mBinding.flCreateDialog.isVisible = true
            }
        }
        mBinding.clCreateRole.clickable {
            dismissDialog()
            startPage<CreateRoleActivity>(
                "edit_model" to  false
            )
        }
        mBinding.clCreateImage.clickable {
            dismissDialog()
            startPage<AiGenerationActivity>()
        }
        FlowBus.flowOf<HomeSelect>().onEach { mBinding.fragment.currentItem = it.index }.launchIn(lifecycleScope)
        AdmobManager.initTimer()
        onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                if(mBinding.llCreateDialog.isVisible || mBinding.flCreateDialog.isVisible) {
                     dismissDialog()
                } else {
                    if (doubleExit) {
                        doubleExit = false
                        moveTaskToBack(true)
                    } else {
                        doubleExit = true
                        showToast(getString(R.string.press_again_to_exit))
                        lifecycleScope.launch {
                            delay(2000)
                            doubleExit = false
                        }
                    }
                }
            }
        })
        showUmp()
        showDialog()
    }

    private fun dismissDialog() {
        mBinding.llCreateDialog.isVisible = false
        mBinding.flCreateDialog.isVisible = false
        mBinding.create.isSelected = false
        selectTab(mBinding.fragment.currentItem)
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        if (intent.getIntExtra("position", 0) == 1) {
            mBinding.home.callOnClick()
        } else if (intent.getIntExtra("position", 0) == 2) {
            mBinding.chat.callOnClick()
        }else if (intent.getIntExtra("position", 0) == 3) {
            mBinding.mine.callOnClick()
            if(intent.getBooleanExtra("role", false)) {
                FlowBus.post(HomeShowRole())
            }
            if(intent.getBooleanExtra("task", false)) {
                FlowBus.post(HomeShowTask())
            }
        }
    }

    private fun selectTab(position: Int) {
        mBinding.home.isSelected = position == 0
        mBinding.chat.isSelected = position == 1
        mBinding.mine.isSelected = position == 2
        mBinding.fragment.currentItem = position
    }

    private fun showUmp() {
        val debugSettings = ConsentDebugSettings.Builder(this)
            .setDebugGeography(ConsentDebugSettings.DebugGeography.DEBUG_GEOGRAPHY_EEA)
            .addTestDeviceHashedId("").build()
        val params = ConsentRequestParameters.Builder().apply {
            if (BuildConfig.DEBUG) setConsentDebugSettings(debugSettings)
        }.build()
        val consentInformation = UserMessagingPlatform.getConsentInformation(this)
        consentInformation.requestConsentInfoUpdate(this, params, {
            if (consentInformation.consentStatus == ConsentInformation.ConsentStatus.REQUIRED || consentInformation.canRequestAds()
                    .not()
            ) {
                KVStore.showUMP = true
            }
            UserMessagingPlatform.loadAndShowConsentFormIfRequired(this) {
            }
        }, {})
    }

    private fun showLovelyLifecycle() {
        if (UserManager.isVip().not() && UserManager.isB() && LovelyLifecycleManager.isEnable()) {
            if (!DateUtils.isToday(KVStore.virtualShowTime)) {
                KVStore.virtualShowTime = System.currentTimeMillis()
                lifecycleLauncher.launch(Intent(this, LifecycleActivity::class.java))
                return
            }
        }
        showNotifyPermission()
    }

    private fun showDialog() {
        if (KVStore.system?.guidDetail?.up == 1) {
            AppUpgradeDialog().setOnDismissListener(object :
                BaseDialogFragment.OnDialogListener {
                override fun onDialogDismiss() {
                    showBDialog()
                }

            }).show(supportFragmentManager)
        } else {
            showBDialog()
        }

    }

    private fun showBDialog() {
        if (UserManager.isB() && !KVStore.agreeLimit) {
            AdultDialog().apply {
                setOnDismissListener(object : OnDialogListener {
                    override fun onDialogDismiss() {
                        showSingInDialog()
                    }
                })
            }.show(supportFragmentManager)
        } else {
            showSingInDialog()
        }
    }

    private fun showSingInDialog() {
        SignDialog.showDialog(this, launcher) {
            showLovelyLifecycle()
        }
    }

    override fun onResume() {
        super.onResume()
        preferentialConditionShow()
    }

    private fun preferentialConditionShow() {
        if (PreferentialManager.isSecondLevelPageShown) {
            if (PreferentialManager.isEnable) {
                if (UserManager.isB() && UserManager.isVip()) {
                    if (DateUtils.isToday(KVStore.discountShowTime).not()) {
                        PreferentialDialog().show(supportFragmentManager)
                    }
                }
            }
        }
    }

    private fun showNotifyPermission() {
        if (!KVStore.hasShowNotifyPermission && !NotificationManagerCompat.from(this)
                .areNotificationsEnabled()
        ) {
            KVStore.hasShowNotifyPermission = true
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                if (ContextCompat.checkSelfPermission(
                        this,
                        Manifest.permission.POST_NOTIFICATIONS
                    ) != PackageManager.PERMISSION_GRANTED
                ) {
                    ActivityCompat.requestPermissions(
                        this,
                        arrayOf(Manifest.permission.POST_NOTIFICATIONS),
                        101
                    )
                }
            } else {
                showLovelyDialog {
                    setDialogTitle(getString(R.string.notify_dialog_title))
                    setDialogMessage(getString(R.string.notify_dialog_content))
                    setPositiveButton {
                        setNotifyPermission()
                    }
                }
            }
        }
    }


    private inner class FragmentAdapter : FragmentStateAdapter(this) {

        override fun getItemCount(): Int {
            return 3
        }

        override fun createFragment(position: Int): Fragment {
            return when (position) {
                0 -> HomeFragment()
                1 -> ChatMsgFragment()
                else -> MineFragment()
            }
        }
    }

}
